package com.diy.common.dao.page;

import com.diy.common.dao.TotalCountContainer;
import com.diy.common.helper.StringUtil;
import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.apache.ibatis.session.RowBounds;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

/**
 * Created by GY on 2015/11/30.
 */
public abstract class AbstractPagingInterceptor implements Interceptor {

    private static final String PROPS_SUFFIX = "suffix";
    private static final String DEFAULT_SUFFIX = "Paging";

    private String suffix;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
        BoundSql boundSql = statementHandler.getBoundSql();
        String oldSql = boundSql.getSql();
        if (StringUtil.isNotEmpty(oldSql)) {
            MetaObject metaObject = SystemMetaObject.forObject(statementHandler);
            MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("delegate.mappedStatement");
            if (mappedStatement.getId().endsWith(suffix)) {
                RowBounds rowBounds = (RowBounds) metaObject.getValue("delegate.rowBounds");
                String newSql = getNewSql(oldSql, rowBounds);

                metaObject.setValue("delegate.boundSql.sql", newSql);
                metaObject.setValue("delegate.rowBounds.offset", RowBounds.NO_ROW_OFFSET);
                metaObject.setValue("delegate.rowBounds.limit", RowBounds.NO_ROW_LIMIT);

                Connection connection = (Connection) invocation.getArgs()[0];
                ParameterHandler parameterHandler = statementHandler.getParameterHandler();

                int totalCount = getTotalCount(connection, boundSql, parameterHandler);
                TotalCountContainer.set(totalCount);
            }
        }
        return invocation.proceed();
    }

    public abstract String getNewSql(String oldSql, RowBounds rowBounds);

    @Override
    public Object plugin(Object target) {
        if (target instanceof StatementHandler) {
            return Plugin.wrap(target, this);
        }
        return target;
    }

    @Override
    public void setProperties(Properties properties) {
        suffix = properties.getProperty(PROPS_SUFFIX, DEFAULT_SUFFIX);
    }

    private int getTotalCount(Connection connection, BoundSql boundSql, ParameterHandler parameterHandler) throws SQLException {
        int result = 0;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            String sql = boundSql.getSql();
            if (sql.contains("LIMIT")) {
                sql = sql.substring(0, sql.indexOf("LIMIT"));
            }
            String countSql = "SELECT count(1) FROM (" + sql + ") temp";
            ps = connection.prepareStatement(countSql);
            parameterHandler.setParameters(ps);
            rs = ps.executeQuery();
            if (rs.next()) {
                result = rs.getInt(1);
            }
        } finally {
            if (ps != null) {
                ps.close();
            }
            if (rs != null) {
                rs.close();
            }
        }
        return result;
    }
}